// Created by wangliang on 2025/3/4.

import 'dart:convert';

import 'package:flutter_app_demo/model/account.dart';
import 'package:flutter_app_demo/model/user_info.dart';
import 'package:flutter_app_demo/net/api_exception.dart';
import 'package:flutter_app_demo/net/common_api.dart';
import 'package:flutter_app_demo/utils/logger.dart';
import 'package:shared_preferences/shared_preferences.dart';

class AccountHelper {
  AccountHelper._();

  static final AccountHelper _instance = AccountHelper._();

  static AccountHelper get instance => _instance;
  static const String _accountKey = "account";
  static const String _userInfoKey = "userInfo";

  Account? account;
  UserInfo? userInfo;

  Future loadAccount() async {
    var prefs = await SharedPreferences.getInstance();
    var accountJson = prefs.getString(_accountKey);
    if (accountJson != null) {
      account = Account.fromJson(json.decode(accountJson));
    }
  }

  bool isLogin() {
    return account?.accessToken != null;
  }

  String? getAccessToken() {
    if (account == null) {
      return null;
    }
    return account!.accessToken;
  }

  String? getRefreshToken() {
    if (account == null) {
      return null;
    }
    return account!.refreshToken;
  }

  Future<String?>? _refreshing;

  Future<String?> _refreshToken() async {
    String? refreshToken = getRefreshToken();
    if (refreshToken == null) {
      return null;
    }
    try {
      Account? resp = await CommonApi.refreshToken(refreshToken);
      account?.refreshToken = resp?.refreshToken;
      account?.accessToken = resp?.accessToken;
      if (account != null) {
        await saveAccount(account!);
      }
      return resp?.accessToken;
    } on ApiException catch (e) {
      Log.e("refreshToken error code: ${e.code}, message: ${e.message}");
      return null;
    }
  }

  Future<String?> refreshToken() async {
    // 如果正在刷新，直接返回已有的 Future
    if (_refreshing != null) return _refreshing!;
    _refreshing = _refreshToken();
    return _refreshing!;
  }

  clearRefreshFuture() {
    _refreshing = null;
  }

  Future saveAccount(Account account) async {
    var prefs = await SharedPreferences.getInstance();
    this.account = account;
    String accountJson = json.encode(account.toJson());
    await prefs.setString(_accountKey, accountJson);
  }

  Future updateUser(UserInfo user) async {
    var prefs = await SharedPreferences.getInstance();
    userInfo = user;
    await prefs.setString(_userInfoKey, json.encode(user.toJson()));
  }

  Future syncServerUser() async {
    try {
      UserInfo? userInfo = await CommonApi.userInfo();
      if (userInfo != null) {
        await updateUser(userInfo);
      }
    } on ApiException catch (e) {
      Log.e("syncServerUser error code: ${e.code}, message: ${e.message}");
    }
  }

  Future clear() async {
    var prefs = await SharedPreferences.getInstance();
    await prefs.remove(_userInfoKey);
    userInfo = null;
  }
}
